package com.sunnada.demo.shiro;

import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.thymeleaf.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

import static org.springframework.http.HttpHeaders.AUTHORIZATION;

/**
 * @BelongsProject: mybatisproject2
 * @BelongsPackage: com.sunnada.demo.shiro
 * @Author: 李瑞益
 * @CreateTime: 2018-10-10 18:45
 * @Description: 第一步，读取sessionid
 */
public class SessionManage extends DefaultWebSessionManager {
    private static final String AUTHORIZTION = "Authorization";
    private static final String REFERENCED_SESSION_ID_SOURCE = "StateLess request";

    public SessionManage() {
        super();
    }

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        String id = WebUtils.toHttp(request).getHeader(AUTHORIZATION);
        System.out.print("session manager's getSessionid()");
        //如果请求头中有Authorization 则其值为 sessionid
        if(!StringUtils.isEmpty(id)){
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,REFERENCED_SESSION_ID_SOURCE);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID,id);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID,Boolean.TRUE);
            return id;
        }else{
            //否则按默认规则从cookie中取sessionid
            return super.getSessionId(request,response);
        }

    }
}
